package com.probiz.estore.catalog.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;

import com.probiz.estore.Constants;
import com.probiz.estore.catalog.dao.VirtualCategoryDao;
import com.probiz.estore.catalog.model.VirtualCategoryFullyModel;
import com.probiz.estore.catalog.model.VirtualCategorySearchCriteria;
import com.probiz.estore.catalog.service.VirtualCategoryManager;
import com.probiz.estore.catalog.service.VirtualcatProdRelationManager;
import com.probiz.estore.catalog.util.CatalogCodeGenerator;
import com.probiz.estore.common.model.catalog.VirtualCategory;
import com.probiz.estore.core.search.SearchCriteria;
import com.probiz.estore.core.util.I18nUtil;


/**
 * Manager implementation for VirtualCategory, responsible for business processing, and communicate between web and persistence layer.
 */
public class VirtualCategoryManagerImpl extends BaseCategoryManagerImpl<VirtualCategory> implements VirtualCategoryManager {

    private VirtualCategoryDao virtualCategoryDao = null;
    private VirtualcatProdRelationManager virtualcatProdRelationManager = null;
    
    public void setVirtualCategoryDao(VirtualCategoryDao virtualCategoryDao) {
		this.virtualCategoryDao = virtualCategoryDao;
	}
    

	public void setVirtualcatProdRelationManager(
			VirtualcatProdRelationManager virtualcatProdRelationManager) {
		this.virtualcatProdRelationManager = virtualcatProdRelationManager;
	}


	/*
      * (non-Javadoc)
      *
      * @see com.probiz.estore.core.service.impl.GenericManagerImpl#init()
      */
    @Override
    protected void initManager() {
        dao = virtualCategoryDao;
        categoryDao = virtualCategoryDao;
    }

    /*
      * (non-Javadoc)
      *
      * @see com.probiz.estore.core.service.impl.GenericManagerImpl#onDelete(java.lang.Object)
      */
    @Override
    protected void preDelete(VirtualCategory entity) {

    }

    /*
      * (non-Javadoc)
      *
      * @see com.probiz.estore.core.service.impl.GenericManagerImpl#onSave(java.lang.Object)
      */
    @Override
    protected void preSave(VirtualCategory entity) {

    }

    /*
     * (non-Javadoc)
     * @see com.probiz.estore.catalog.service.VirtualCategoryManager#saveFully(com.probiz.estore.catalog.model.VirtualCategoryFullyModel)
     */
    public Map<String, Object>  saveFully(VirtualCategoryFullyModel model){
    	VirtualCategory category = model.getVirtualCategory();
    	Map<String, Object> returnMsgs = new HashMap<String, Object>();
    	
    	 //start:设置目录编码并检查
		if(StringUtils.isBlank(category.getCategoryCode())){
			boolean isCodeAvailable = false;
			do{
				String code = CatalogCodeGenerator.generateVirtualCategoryCode();
				Long size = virtualCategoryDao.getSizeByCategoryCodeByNotCategoryId(code, category.getCategoryId());
				if(size==0){
					//该编码可用
					isCodeAvailable = true;
					category.setCategoryCode(code);
				}
			}while(!isCodeAvailable);
		}else{
			//用getSizeByCategoryCodeByNotCategoryId而不用getByCode的原因在于调用后者的时候会有update操作，造成数据库有两个相同code的商品，出错
			Long size = virtualCategoryDao.getSizeByCategoryCodeByNotCategoryId(category.getCategoryCode(), category.getCategoryId());
			
			if(size>=1){
				//编码重复
				returnMsgs.put("error", I18nUtil.getInstance().getMessage("virtualCategory.categoryCode.repeated"));
				evict(category); //必须把evict出session 否则会有update操作
				return returnMsgs;
			}
		}
		//end:设置目录编码并检查
		
		
    	// start:新增赋值
        if (null == category.getCategoryId()) {
            // case:新增
        	VirtualCategory parent = virtualCategoryDao.getById(category.getParentId());
            category.setDepth((short) (parent.getDepth() + 1));
            category.setItemCount(0);
            category.setActiveItemCount(0);
            category.setParentPath(parent.getCategoryPath());
            category.setCategoryPath("");//临时,必须等categoryId出来后才能再次保存
            category.setHasChildren(Constants.FLAG_FALSE);
            category.setSortOrder(VirtualCategory.SORTORDER_DEFAULT_VALUE);
            // 保存父亲
            parent.setHasChildren(Constants.FLAG_TRUE);
            virtualCategoryDao.save(parent);
            
            virtualCategoryDao.save(category);
            // start:保存categoryPath	
            category.setCategoryPath(parent.getCategoryPath()+category.getCategoryId()+".");
            virtualCategoryDao.save(category);
            // end:保存categoryPath	
        }
        // end:新增赋值
        
        this.save(category);
        // start:保存专场商品
        virtualcatProdRelationManager.saveRecommendedProductsFromArrays(model.getVirtualCategory(),model.getRecommendedProductIds());
        // end:保存专场商品
        
        return returnMsgs;
    }
    /*
     * (non-Javadoc)
     * @see com.probiz.estore.catalog.service.VirtualCategoryManager#deleteFully(com.probiz.estore.common.model.catalog.VirtualCategory)
     */
    public Map<String, Object> deleteFully(VirtualCategory category) {
        Map<String, Object> returnMsgs = new HashMap<String, Object>();
    	
    	returnMsgs.put("categoryId", category.getCategoryId());
    	if (category.getCategoryId() == 1) {
            // case:如果是根目录
    		returnMsgs.put("result", -1);
    		returnMsgs.put("message", I18nUtil.getInstance().getMessage("virtualCategory.del.root"));
        } else if (!countSubCategoryById(category.getCategoryId()).equals(new Integer("0"))) {
            // case:如果包含子目录
        	returnMsgs.put("result", -2);
        	returnMsgs
                    .put("message",I18nUtil.getInstance().getMessage("virtualCategory.del.containSubCat"));
        }  else {
            // otherwise:成功删除
           
            // 获得父id
            Integer parentId = category.getParentId();
            VirtualCategory parent = virtualCategoryDao.getById(category.getParentId());
            Integer subCategoryCount = virtualCategoryDao.countSubCategoryById(parent.getCategoryId());
            if (subCategoryCount.compareTo(new Integer("1")) <= 0) {
                parent.setHasChildren(Constants.FLAG_FALSE);
                virtualCategoryDao.save(parent);
            }
            virtualCategoryDao.delete(category);
            returnMsgs.put("result", 1);
            returnMsgs.put("message", I18nUtil.getInstance().getMessage("virtualCategory.del.success"));
            returnMsgs.put("parentId", parentId);
        }
    	
		return returnMsgs;

    }
    /*
     * (non-Javadoc)
     * @see com.probiz.estore.catalog.service.VirtualCategoryManager#getCategoryByCode(java.lang.String)
     */
    public VirtualCategory getCategoryByCode(String categoryCode) {
        return virtualCategoryDao.getCategoryByCode(categoryCode);
    }

    /*
     * (non-Javadoc)
     * @see com.probiz.estore.catalog.service.VirtualCategoryManager#searchByCriteria(com.probiz.estore.catalog.model.VirtualCategorySearchCriteria, com.probiz.estore.core.search.SearchCriteria)
     */
    public List<VirtualCategory> searchByCriteria(VirtualCategorySearchCriteria virtualCategorySearchCriteria, SearchCriteria searchCriteria) {
        return virtualCategoryDao.searchByCriteria(virtualCategorySearchCriteria, searchCriteria);
    }

    /*
     * (non-Javadoc)
     * @see com.probiz.estore.catalog.service.VirtualCategoryManager#convertListToJSONArray(java.util.List)
     */
    public JSONArray convertListToJSONArray(List<VirtualCategory> categoryList) {
        JSONArray categoryArray = new JSONArray();
        for (VirtualCategory category : categoryList) {
            JSONObject categoryJSON = new JSONObject();
            categoryJSON.put("categoryId", category.getCategoryId());
            categoryJSON.put("categoryCode", category.getCategoryCode());
            categoryJSON.put("categoryName", category.getCategoryName());
            categoryJSON.put("depth", category.getDepth());
            categoryJSON.put("hasChildren", category.getHasChildren());
            categoryJSON.put("parentId", category.getParentId());
            categoryJSON.put("categoryPath", category.getCategoryPath());
            categoryJSON.put("simpleCategoryPathName", category
                    .getSimpleCategoryPathName());
            categoryJSON.put("itemCount", category.getItemCount());
            categoryJSON.put("activeItemCount", category.getActiveItemCount());
            categoryArray.add(categoryJSON);
        }
        return categoryArray;
    }


    /*
     * (non-Javadoc)
     * @see com.probiz.estore.catalog.service.VirtualCategoryManager#getCategoryIdByUri(java.lang.String)
     */
    public Integer getCategoryIdByUri(String uri) {
        String categoryId = uri.substring(uri.lastIndexOf("cat"), uri
                .lastIndexOf("."));
        categoryId = categoryId.substring("cat".length());
        return Integer.valueOf(categoryId);
        
    }

   /*
    * (non-Javadoc)
    * @see com.probiz.estore.catalog.service.VirtualCategoryManager#getUriByCategoryId(java.lang.Integer)
    */
    public String getUriByCategoryId(Integer categoryId) {
        StringBuffer url = new StringBuffer();
        url.append("/vir");
        for (VirtualCategory virtualCategory : virtualCategoryDao.getNavigationCategories(categoryId)) {
            url.append("-");
            url.append(virtualCategory.getCategoryCode());
        }
        url.append("/cat");
        url.append(categoryId.toString());
        url.append(".html");
        return url.toString();
    }

    /*
     * (non-Javadoc)
     * @see com.probiz.estore.catalog.service.VirtualCategoryManager#getNavigationCategories(java.lang.Integer)
     */
    public List<VirtualCategory> getNavigationCategories(Integer categoryId) {
        return virtualCategoryDao.getNavigationCategories(categoryId);
	}

	

}
